package jsc.acid;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import jsc.base.JSCerror;
import jsc.base.TextFileReader;
import jsc.base.TextFileWriter;
import jsc.base.WordEnumerator;

/**
 * This class provides methods to process a Text, wich is a file containing intelligible words,
 * a text is first of all a text so it would be pointless to create a Text without a file, 
 * this is why it can't be done
 * 
 * @author Alec Ermis, Maxime Rihouey
 *
 */
public class Text {

	private String text;
	private ArrayList<Word> wordList; // list of the words of the text
	private File file;

	// constructors
	public Text(TextFileReader reader, File file){
		text = "";
		wordList = new ArrayList<Word>();
		this.file = file;
		this.makeText(reader);
	}

	public Text(File file) throws IOException{
		this(new TextFileReader(file), file);
	}

	// getters
	public ArrayList<Word> getWords(){
		return wordList;
	}

	// display
	public String toString(){
		return text;
	}

	// methods

	/**
	 * write the specified text in the file and throw the new text
	 */
	public Text update(String newText){
		try {
			TextFileWriter writer = new TextFileWriter(this.file);
			writer.write(newText);
			writer.close();
			return new Text(this.file);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return this;
	}

	/**
	 * make the text from the file of the reader
	 * @param reader
	 */
	private void makeText(TextFileReader reader){
		try {
			WordEnumerator enumerator;
			String line;
			while(!reader.eof()){
				line = reader.read();
				text += line+"\n";
				enumerator = new WordEnumerator(line);
				while(!enumerator.noMoreWord()){
					try {
						int offset = enumerator.offset();
						wordList.add(new Word(line.substring(offset,offset+enumerator.length()),offset));
						enumerator.move();
					} catch (JSCerror e) {
						// TODO Auto-generated catch block
						System.out.println("fonction makeText");
						e.printStackTrace();
					}

				}
			}
			reader.close();
		} catch (IOException e) {System.out.println();
		// TODO Auto-generated catch block
		System.out.println("Impossible d'ouvrir le fichier");
		e.printStackTrace();
		}
	}

	/*
	 * Test
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		System.out.println("###################### Test Positif ################");
		try {

			// test positif
			Text testText = new Text(new File("texts/testHelene.txt"));
			System.out.println(testText.getWords());


		} catch (IOException e) {
			System.out.println("Impossible de trouver le fichier.");
		}

		System.out.println("###################### Test Negatif ################");
		try {

			// test negatif
			Text testText = new Text(new File("texts/testHelene2.txt"));
			System.out.println(testText.getWords());


		} catch (IOException e) {
			System.out.println("Impossible de trouver le fichier.");
		}
	}
}
